package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.common.StringUtils;
import com.stylefeng.guns.modular.huamao.dao.SktSysConfigsMapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.dao.SktAgentsStockholderMapper;

/**
 * <p>
 * 代理公司的股东表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-04-19
 */
@Service
public class SktAgentsStockholderServiceImpl extends ServiceImpl<SktAgentsStockholderMapper, SktAgentsStockholder> implements ISktAgentsStockholderService {
	
	@Autowired
	private SktAgentsStockholderMapper sktAgentsStockholderMapper;

	@Autowired
	private IUsersService iUsersService;
	@Autowired
	private ISktAgentsService iSktAgentsService;
	@Autowired
	private IAgentsApplysService agentsApplysService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private 	ISktAgentsAccountService  sktAgentsAccountService;
	@Autowired
	private ISktAgentsChangesService sktAgentsChangesService;
	@Autowired
	private SktSysConfigsMapper sysConfigsMapper;
	private final String SUCCESS = "SUCCESS";
	private final String FALSE = "FALSE";
	private final String TYPE = "TYPE";//用户类型
	private final String ISAGENTS = "ISAGENTS";//是否是管理股东
	private final String AUDITSTATUS = "AUDITSTATUS";//是否实名认证
	private final String HASAGENT = "HASAGENT";// 已有该股东
	
	@Override
	public List<SktAgentsStockholderDTO> showSktStcokHolderInfo(Page<SktAgentsStockholderDTO> page,SktAgentsStockholderDTO sktAgentsStockholderDTO) {
		List<SktAgentsStockholderDTO> list = sktAgentsStockholderMapper.showSktStcokHolderInfo(page,sktAgentsStockholderDTO);
		Integer total = sktAgentsStockholderMapper.showSktStcokHolderInfoCount(sktAgentsStockholderDTO);
		page.setTotal(total);
		return list;
	}

	@Override
	public String selectSktStcokManger(Integer agentId, Integer type) {

		SktAgentsStockholder sktAgentsStockholder = sktAgentsStockholderMapper.selectSktStcokManger(agentId, type);
		if(ToolUtil.isEmpty(sktAgentsStockholder)){
			return SUCCESS;
		}
		return FALSE;
	}

	@Override
	public Map<String, Object> selectNameOrPhone(String nameOrPhone) {
		Map<String,Object> map = sktAgentsStockholderMapper.selectNameOrPhone(nameOrPhone);
		return map;
	}

	@Override
	public void updateSktAgentsStockHolder(SktAgentsStockholder sktAgentsStockholder) {
		sktAgentsStockholderMapper.updateSktAgentsStockHolder(sktAgentsStockholder);
	}

	@Override
	@Transactional
	public String insertSktStockHodler(SktAgentsStockholderDTO sktAgentsStockholder) {
		//判断用户信息 如实名认证 管理层
		Map<String,Object> usersMap = sktAgentsStockholderMapper.selectUserById(sktAgentsStockholder.getUserId());
		if(usersMap.containsKey("userType") && "0".equals(usersMap.get("userType"))){
			return TYPE;
		}
		if(usersMap.containsKey("isAgent") && !"false".equals(usersMap.get("isAgent").toString())){
			return ISAGENTS;
		}
		if(usersMap.containsKey("auditStatus") && !"1".equals(usersMap.get("auditStatus"))){
			return AUDITSTATUS;
		}
		//根据省市县判断地区
		Integer alevel = sktAgentsStockholder.getAlevel();
		//是否有该职位
		Map<String, Object> map = getMap(alevel,sktAgentsStockholder);
		if(map != null){
			return HASAGENT;
		}
		try {
			//获取代理公司id
			Map<String, Object> map2 = getMap2(alevel,sktAgentsStockholder);
			//新增股东申请表
			SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
			agentsStockholder.setAgentId(Integer.parseInt(map2.containsKey("agentId")?map2.get("agentId").toString():null));
			agentsStockholder.setUserId(sktAgentsStockholder.getUserId());
			agentsStockholder.setType(sktAgentsStockholder.getType());
			agentsStockholder.setStockNum(sktAgentsStockholder.getType()==1?5:1);
			agentsStockholder.setStoreNum(0);
			agentsStockholder.setCreateTime(DateUtil.parseTime(DateUtil.getTime()));
			sktAgentsStockholderMapper.insert(agentsStockholder);
			//修改用户表
			Users users = new Users();
			users.setUserId(sktAgentsStockholder.getUserId());
			users.setIsAgent(sktAgentsStockholder.getAlevel());
			iUsersService.updateById(users);
			//修改代理公司表
			SktAgents sktAgents = new SktAgents();
			sktAgents = iSktAgentsService.selectById(map2.containsKey("agentId")?map2.get("agentId").toString():null);
			sktAgents.setStockNum(sktAgents.getStockNum()+1);
			if(sktAgentsStockholder.getType()==1){
				sktAgents.setGPsurplusStockNum(sktAgents.getTotalStockNum()-5);
			}else{
				sktAgents.setGPsurplusStockNum(sktAgents.getTotalStockNum()-1);
			}
			iSktAgentsService.updateById(sktAgents);
			return SUCCESS;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return FALSE;
		}
	}
	
	
	public Map<String,Object> getMap(Integer alevel, SktAgentsStockholderDTO sktAgentsStockholder){
		Map<String, Object> map = null;
		if(alevel==10){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					null,null,sktAgentsStockholder.getAlevel(),sktAgentsStockholder.getType());
		}else if(alevel ==  11){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					sktAgentsStockholder.getCitys(),null,sktAgentsStockholder.getAlevel(),sktAgentsStockholder.getType());
		}else if(alevel == 12){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					sktAgentsStockholder.getCitys(),sktAgentsStockholder.getCounty(),sktAgentsStockholder.getAlevel(),sktAgentsStockholder.getType());
		}
		return map;
	}
	
	public Map<String,Object> getMap2(Integer alevel, SktAgentsStockholderDTO sktAgentsStockholder){
		Map<String, Object> map = null;
		if(alevel==10){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					null,null,sktAgentsStockholder.getAlevel(),null);
		}else if(alevel ==  11){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					sktAgentsStockholder.getCitys(),null,sktAgentsStockholder.getAlevel(),null);
		}else if(alevel == 12){
			map  = 	sktAgentsStockholderMapper.selectSktAgentsStockUser(sktAgentsStockholder.getProvince(),
					sktAgentsStockholder.getCitys(),sktAgentsStockholder.getCounty(),sktAgentsStockholder.getAlevel(),null);
		}
		return map;
	}
	@Override
	@Transactional
	public Map<String,Object> agentTransfer(Integer shId,Integer transferUserId){
		Map<String,Object> map=new  HashMap();
		try{
			if (shId.equals(transferUserId)){
				map.put("code","00");
				map.put("msg","不能转移给自己");
				return  map;
			}
			Users shareUsers = iUsersService.selectById(shId);
			if(shareUsers==null){
				map.put("code","00");
				map.put("msg","股东不存在");
				return  map;
			}
			Users transferUsers = iUsersService.selectById(transferUserId);
			if (transferUsers==null){
				map.put("code","00");
				map.put("msg","被转移人不存在");
				return  map;
			}
			if (transferUsers.getTrueName()==null ||"".equals(transferUsers.getTrueName())){
				map.put("code","00");
				map.put("msg","被转移人未实名");
				return  map;
			}
			if (transferUsers.getIsAgent()!=0 ){
				map.put("code","00");
				map.put("msg","被转移人是股东不能进行转移");
				return  map;
			}
			SktAgentsStockholder sktAgentsStockholder = sktAgentsStockholderMapper.selectByUserId(shId);
			sktAgentsStockholder.setUserId(transferUserId);
			sktAgentsStockholderMapper.updateById(sktAgentsStockholder);
			shareUsers.setIsAgent(0);
			iUsersService.updateById(shareUsers);
			transferUsers.setIsAgent(sktAgentsStockholder.getType());
			iUsersService.updateById(transferUsers);
			AgentsApplys agentsApplys=new AgentsApplys();
			agentsApplys.setAgentId(sktAgentsStockholder.getAgentId());
			agentsApplys.setUserId(shId);
			agentsApplys.setStatus(3);
			EntityWrapper<AgentsApplys>  entityWrapper=new EntityWrapper<AgentsApplys>(agentsApplys);
			AgentsApplys agentsApplys1 = agentsApplysService.selectOne(entityWrapper);
			SktAgentsChanges shareAgentChenge = getAgentChenge(sktAgentsStockholder.getAgentId(), 3, shId, sktAgentsStockholder.getType(), 0, 0);
			sktAgentsChangesService.insert(shareAgentChenge);
			SktAgentsChanges transferAgentChenge = getAgentChenge(sktAgentsStockholder.getAgentId(), 4, transferUserId, 0, sktAgentsStockholder.getType(), 0);
			sktAgentsChangesService.insert(transferAgentChenge);
            agentsApplys1.setUserId(transferUserId);
            agentsApplys1.setPhone(transferUsers.getUserPhone());
            agentsApplysService.updateById(agentsApplys1);
			map.put("code","01");
			map.put("msg","操作成功");
			return  map;
		}catch (Exception e){
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","操作失败");
			return  map;
		}
	}


	public SktAgentsChanges  getAgentChenge(Integer agentId,Integer type,Integer userId,Integer preRole,Integer afterRole,Integer stockNum){
		SktAgentsChanges sktAgentsChanges=new SktAgentsChanges();
		String orderNo = StringUtils.getOrderIdByTime("S");
		sktAgentsChanges.setChangeNo(orderNo);
		sktAgentsChanges.setAgentId(agentId);
		sktAgentsChanges.setType(type);
		sktAgentsChanges.setUserId(userId);
		sktAgentsChanges.setPreRole(preRole);
		sktAgentsChanges.setAfterRole(afterRole);
		sktAgentsChanges.setStockNum(stockNum);
		sktAgentsChanges.setCreateTime(new Date());
		return sktAgentsChanges;
	}

	/**
	 *  股东升级
	 * @param  typeRe  变化后的类型
	 * @param type 变化类型   1  降级  2 升级
	 * @param shId  股东id
	 * @return
	 */
	@Override
	@Transactional
	public   Map<String,Object> change( Integer type,Integer shId,Integer typeRe){
		Map<String,Object> map=new  HashMap();
		try{
            SktAgentsStockholder sktAgentsStockholder = sktAgentsStockholderMapper.selectById(shId);
            //现在拥有股份数
            Integer stockNumHolder=sktAgentsStockholder.getStockNum();
            Integer userId=sktAgentsStockholder.getUserId();
            Integer	agentId	=sktAgentsStockholder.getAgentId();
            SktAgents sktAgents = iSktAgentsService.selectById(agentId);
            SktAgentsAccount agentsAccount=new SktAgentsAccount();//代理公司账号
            agentsAccount.setAgentId(agentId);
            EntityWrapper<SktAgentsAccount> wep=new EntityWrapper<SktAgentsAccount>(agentsAccount);
            SktAgentsAccount sktAgentsAccount = sktAgentsAccountService.selectOne(wep);
            Integer agencyFee = sktAgents.getAgencyFee();//每股缴纳代理费
            //不同类型对应的股份数
            Integer stockNumTypeRe=0;
            //升级操作
            if (type==2){
                Integer shType=sktAgentsStockholder.getType();
                if (shType<7){
                    map.put("code","00");
                    map.put("msg","管理股东不能升级");
                    return map;
                }

                if (stockNumHolder>1){
                    map.put("code","00");
                    map.put("msg","该用户已经降级不能在升级");
                    return map;
                }
                if (typeRe==7){
                    map.put("code","00");
                    map.put("msg","只能升级为管理股东");
                    return map;
                }


                SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
                agentsStockholder.setAgentId(agentId);
                agentsStockholder.setType(typeRe);
                //要变动后股东类型对应的人数
                Integer countStcokManger = 	sktAgentsStockholderMapper.selectCountStcokManger(agentsStockholder);

                if (typeRe == 1 ) {
                    if (countStcokManger == 1){
                        map.put("code","00");
                        map.put("msg","董事长职位已满");
                        return map;
                    }
                    stockNumTypeRe=5;
                } else if (typeRe == 2  ) {
                    if (countStcokManger == 1){
                        map.put("code","00");
                        map.put("msg","总裁职位已满");
                        return map;
                    }
                    stockNumTypeRe=4;
                } else if (typeRe == 3 ) {
                    if (countStcokManger == 1){
                        map.put("code","00");
                        map.put("msg","行政职位已满");
                        return map;
                    }
                    stockNumTypeRe=3;
                } else if (typeRe == 4 ) {
                    if (countStcokManger == 1){
                        map.put("code","00");
                        map.put("msg","财务职位已满");
                        return map;
                    }
                    stockNumTypeRe=3;
                } else if (typeRe == 5 ) {
                    if (countStcokManger == 3){
                        map.put("code","00");
                        map.put("msg","部门经理职位已满");
                        return map;
                    }
                    stockNumTypeRe=2;
                }
                //补交股份数
                Integer	stockNumDiff=stockNumTypeRe-stockNumHolder;
                //插入变更表
                SktAgentsChanges transferAgentChenge = getAgentChenge( sktAgentsStockholder.getAgentId(), 1, sktAgentsStockholder.getUserId(),  sktAgentsStockholder.getType(),typeRe, stockNumDiff);
                sktAgentsChangesService.insert(transferAgentChenge);
                //更新股东表
                sktAgentsStockholder.setStockNum(stockNumTypeRe);
                sktAgentsStockholder.setType(typeRe);
                sktAgentsStockholderMapper.updateById(sktAgentsStockholder);
                //更新用户表
                Users users = iUsersService.selectById(userId);
                users.setIsAgent(typeRe);
                iUsersService.updateById(users);
                //更新代理公司剩余股份数
                sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()-stockNumTypeRe);
                sktAgents.setLPsurplusStockNum(sktAgents.getLPsurplusStockNum()+stockNumHolder);
                iSktAgentsService.updateById(sktAgents);
                //更新股东申请表
                AgentsApplys agentsApplys=new AgentsApplys();
                agentsApplys.setAgentId(agentId);
                agentsApplys.setUserId(userId);
                agentsApplys.setStatus(3);
                EntityWrapper<AgentsApplys>  eWrapper=new EntityWrapper<AgentsApplys>(agentsApplys);
                AgentsApplys agentsApplys1 = agentsApplysService.selectOne(eWrapper);
				Calendar c = Calendar.getInstance();
				c.setTime(new Date());//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				Date testTime=c.getTime();
				agentsApplys1.setTestTime(testTime);
				agentsApplys1.setBatFlag(1);
				agentsApplys1.setBatTime(testTime);
                agentsApplys1.setType(typeRe);
                agentsApplys1.setStockNum(stockNumTypeRe);
                int moneys=stockNumTypeRe*agencyFee;
                BigDecimal money=new BigDecimal(moneys);
                agentsApplys1.setMoney(money);
                agentsApplys1.setRemark("股东升级");
                agentsApplysService.updateById(agentsApplys1);
                //给本人发几份
                Account account=new Account();
                account.setUserId(userId);
                EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
                Account account1 = accountService.selectOne(entityWrapper);
                BigDecimal scoreAdd= new BigDecimal(agencyFee).multiply(new BigDecimal(100));//补交代理费所得积分
                //积分流水
                accountService.insertLogScore(0,9,transferAgentChenge.getChangeNo(),account1.getScore(),"升级代理公司股东，赠送积分到积分账户",scoreAdd,1,userId);
                account1.setScore(account1.getScore().add(scoreAdd));
                account1.setTotalScore(account1.getTotalScore().add(scoreAdd));
                accountService.updateById(account1);
                //给上线发积分
                int inviteId = users.getInviteId();
                if (inviteId != 0) {
                    Users inviteUsers = iUsersService.selectById(inviteId);
                    if (inviteUsers.getUserType() == 2 && inviteUsers.getIsAgent() != 0) {
                        BigDecimal	doubelScore=scoreAdd.multiply(new BigDecimal(2));
                        Account accountInvite1=new Account();
                        accountInvite1.setUserId(userId);
                        EntityWrapper<Account> ew=new EntityWrapper<Account>(accountInvite1);
                        Account accountInvite = accountService.selectOne(ew);
                        accountService.insertLogScore(userId, 10, transferAgentChenge.getChangeNo(),
                                accountInvite.getScore(), "下线升级代理奖励",doubelScore, 1, inviteId);
                        accountInvite.setScore (accountInvite.getScore().add(doubelScore));
                        accountInvite.setTotalScore (accountInvite.getTotalScore().add(doubelScore));
                        accountService.updateById(accountInvite);
                    }
                }
                //判断代理公司账户是否开启
                Integer runFlag=sktAgentsAccount.getRunFlag();
                if (runFlag==1){
                    accountService.insertScoreAgent(3,agentId,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),1,scoreAdd,"代理升级，代理公司获得");
                    sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(scoreAdd));
                    sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(scoreAdd));
                    sktAgentsAccountService.updateById(sktAgentsAccount);
                }else{
                    //accountService.insertLogScoreFreeze(0,9,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),"代理升级，代理公司获得",scoreAdd,1,userId);
                    accountService.insertScoreAgent(2,agentId,transferAgentChenge.getChangeNo(),sktAgentsAccount.getFreezeScore(),1,scoreAdd,"代理升级，代理公司获得待发积分");
                    sktAgentsAccount.setFreezeScore(sktAgentsAccount.getFreezeScore().add(scoreAdd));
                    sktAgentsAccountService.updateById(sktAgentsAccount);
                }
                //检查开启代理公司运营账号货分红账号
                Map<String, Object> map1 = checkRunOrProfit(agentId, transferAgentChenge.getChangeNo());
                if ("00".equals(map1.get("code").toString())){
                    return map1;
                }

            }
            //降级操作
            if (type==1){
                Integer shType=sktAgentsStockholder.getType();
                if(shType==7){
                    map.put("code","00");
                    map.put("msg","普通股东不能降级");
                    return map;
                }
				if(shType==1){
					map.put("code","00");
					map.put("msg","董事长不能降级");
					return map;
				}
                if (typeRe!=7){
                    map.put("code","00");
                    map.put("msg","只能降级普通股东");
                    return map;
                }
                //插入变更表
                SktAgentsChanges transferAgentChenge = getAgentChenge( sktAgentsStockholder.getAgentId(), 2, sktAgentsStockholder.getUserId(), sktAgentsStockholder.getType(), typeRe,0);
                sktAgentsChangesService.insert(transferAgentChenge);
                //更新股东表
                sktAgentsStockholder.setType(typeRe);
                sktAgentsStockholderMapper.updateById(sktAgentsStockholder);
                //更新用户表
                Users users = iUsersService.selectById(userId);
                users.setIsAgent(typeRe);
                iUsersService.updateById(users);
                //更新代理公司剩余股份数
                sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()+stockNumHolder);
                sktAgents.setLPsurplusStockNum(sktAgents.getLPsurplusStockNum()-stockNumHolder);
                iSktAgentsService.updateById(sktAgents);
                //更新股东申请表
                AgentsApplys agentsApplys=new AgentsApplys();
                agentsApplys.setAgentId(agentId);
                agentsApplys.setUserId(userId);
                agentsApplys.setStatus(3);
                EntityWrapper<AgentsApplys>  eWrapper=new EntityWrapper<AgentsApplys>(agentsApplys);
                AgentsApplys agentsApplys1 = agentsApplysService.selectOne(eWrapper);
				agentsApplys1.setBatFlag(0);
                agentsApplys1.setType(typeRe);
                agentsApplys1.setStockNum(stockNumTypeRe);
                int moneys=stockNumTypeRe*agencyFee;
                BigDecimal money=new BigDecimal(moneys);
                agentsApplys1.setMoney(money);
                agentsApplys1.setRemark("代理股东降级");
                agentsApplysService.updateById(agentsApplys1);
            }
            map.put("code","01");
            map.put("msg","操作成功");
            return  map;
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code","00");
            map.put("msg","操作异常");
            return map;
        }
	}
    //检查开启代理公司运营账号货分红账号
	@Override
	public   Map<String,Object> checkRunOrProfit(Integer agentId,String changeNo){
		Map<String,Object> map=new HashMap<>();
		try{
			SktAgents sktAgents = iSktAgentsService.selectById(agentId);
			SktAgentsAccount agentsAccount=new SktAgentsAccount();//代理公司账号
			agentsAccount.setAgentId(agentId);
			EntityWrapper<SktAgentsAccount> wep=new EntityWrapper<SktAgentsAccount>(agentsAccount);
			SktAgentsAccount sktAgentsAccount = sktAgentsAccountService.selectOne(wep);
			int	stockNum=sktAgents.getStockNum();//当前公司股东人数
			int	totalNum=sktAgents.getTotalNum();//代理公司股东总人数
			int storeNum=sktAgents.getStoreNum();//当前辖区商家数量
			int totalStoreNum=sktAgents.getTotalStoreNum();//完成目标辖区商家数量
			DecimalFormat df=new DecimalFormat("0.000");
			String perStockNums = df.format((float) stockNum / totalNum);
			float perStockNum = Float.parseFloat(perStockNums);
			String perStoreNums = df.format((float) storeNum / totalStoreNum);
			float perStoreNum = Float.parseFloat(perStoreNums);
			//判断代理公司账户是否开启
			Integer runFlag=sktAgentsAccount.getRunFlag();
			//检查开启代理公司的运营账户货分红账户
			if(runFlag==0){
				if (perStockNum>0.5 && perStoreNum>0.5){
					sktAgentsAccount.setRunFlag(1);
					sktAgentsAccount.setRunTime(new Date());
					if (!"".equals(changeNo) && changeNo!=null){
						accountService.insertScoreAgent(32,agentId,changeNo,sktAgentsAccount.getFreezeScore(),-1,sktAgentsAccount.getFreezeScore(),"待发积分转正式");
						accountService.insertScoreAgent(32,agentId,changeNo,sktAgentsAccount.getScore(),1,sktAgentsAccount.getFreezeScore(),"待发积分转正式");
					}
					sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(sktAgentsAccount.getFreezeScore()));
					sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(sktAgentsAccount.getFreezeScore()));
					sktAgentsAccount.setFreezeScore(BigDecimal.ZERO);
					sktAgentsAccountService.updateById(sktAgentsAccount);
				}
			}
			//分红操作
			if(perStockNum>0.7 && perStoreNum>0.7){
				//查询股东直推商家数
				SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
				String fieldValue = sysConfig.getFieldValue();
				Integer holderDividendNum=Integer.parseInt(fieldValue);
				//查询一个股东开是否进行分红
				List<SktAgentsStockholder> list = sktAgentsStockholderMapper.selectByAgentId(agentId);
				if (list!=null && list.size()>0){
					BigDecimal twoFreezeDividend=list.get(0).getTwoFreezeDividend();
					if(twoFreezeDividend.compareTo(BigDecimal.ZERO)==1){
						for (SktAgentsStockholder agentsStockholder:list){
							Integer userId=agentsStockholder.getUserId();
							int totalStockNum=sktAgents.getTotalStockNum();
							BigDecimal twoRatio=sktAgents.getTwoRatio();
							//	int stockNum=agentsStockholder.getStockNum();
							Account account = accountService.selectAccountByuserId(userId);
							Integer countIsStore = iUsersService.selectCountIsStore(userId);
							if(countIsStore>=holderDividendNum){//完成直推任务
								accountService.insertLogScoreFreeze(userId,31,changeNo,agentsStockholder.getTwoFreezeDividend(),"代理公司股东人数和商家人数完成70%的分红划拨",agentsStockholder.getTwoFreezeDividend(),-1,userId);
								accountService.insertLogScore(userId,12,changeNo,account.getScore(),"代理公司股东人数和商家人数完成70%的分红划拨",agentsStockholder.getTwoFreezeDividend(),1,userId);
								account.setScore(account.getScore().add(agentsStockholder.getTwoFreezeDividend()));
								account.setTotalScore(account.getTotalScore().add(agentsStockholder.getTwoFreezeDividend()));
								account.setFreezeScore(account.getFreezeScore().subtract(agentsStockholder.getTwoFreezeDividend()));
								agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
								accountService.updateById(account);
								sktAgentsStockholderMapper.updateById(agentsStockholder);
							}else{//未完成直推任务
								accountService.insertLogScoreFreeze(userId,33,changeNo,agentsStockholder.getTwoFreezeDividend(),"代理公司股东人数和商家人数完成70%的分红划拨但直推商家未完成",agentsStockholder.getTwoFreezeDividend(),-1,userId);
								accountService.insertLogScoreFreeze(userId,17,changeNo,agentsStockholder.getStoreFreezeDividend(),"代理公司股东人数和商家人数完成70%的分红划拨但直推商家未完成",agentsStockholder.getTwoFreezeDividend(),1,userId);
								agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getTwoFreezeDividend()));
								agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
								sktAgentsStockholderMapper.updateById(agentsStockholder);
							}
							//完成100%
							if (stockNum>=totalNum && storeNum>=totalStoreNum){
								if (countIsStore>=holderDividendNum){//完成直推任务
									accountService.insertLogScoreFreeze(userId,31,changeNo,agentsStockholder.getThreeFreezeDividend(),"代理公司任务全部完成的分红划拨",agentsStockholder.getThreeFreezeDividend(),-1,userId);
									accountService.insertLogScore(userId,12,changeNo,account.getScore(),"代理公司任务全部完成的分红划拨",agentsStockholder.getThreeFreezeDividend(),1,userId);
									account.setScore(account.getScore().add(agentsStockholder.getTwoFreezeDividend()));
									account.setTotalScore(account.getTotalScore().add(agentsStockholder.getTwoFreezeDividend()));
									account.setFreezeScore(account.getFreezeScore().subtract(agentsStockholder.getTwoFreezeDividend()));
									agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
									accountService.updateById(account);
									sktAgentsStockholderMapper.updateById(agentsStockholder);
								}else {//未完成直推任务
									accountService.insertLogScoreFreeze(userId,34,changeNo,agentsStockholder.getThreeFreezeDividend(),"代理公司股东人数和商家人数完成70%的分红划拨但直推商家未完成",agentsStockholder.getThreeFreezeDividend(),-1,userId);
									accountService.insertLogScoreFreeze(userId,17,changeNo,agentsStockholder.getStoreFreezeDividend(),"代理公司股东人数和商家人数完成70%的分红划拨但直推商家未完成",agentsStockholder.getThreeFreezeDividend(),1,userId);
									agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getTwoFreezeDividend()));
									agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
									sktAgentsStockholderMapper.updateById(agentsStockholder);
								}
							}

						}

					}
				}
			}
			map.put("code","01");
			map.put("msg","分润操作成功");
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","分润操作失败");
		}
		return map;
	}

	/**
	 * 董事长和监事任命
	 * @param userId
	 * @param alevel
	 * @param provinceId
	 * @param cityId
	 * @param areaId
	 * @param type
	 * @return
	 */
	@Override
	@Transactional
	public Map<String,Object> addShareHolder(Integer userId,Integer alevel,Integer provinceId,Integer cityId,Integer areaId,Integer type,Integer staffId){
		Map<String,Object> map=new  HashMap();
		try{
			//检查用户信息
			Users users = iUsersService.selectById(userId);
			if (users.getTrueName()==null){
				map.put("code","00");
				map.put("msg","必须实名后才能申请该职位");
				return map;
			}
			SktAgents sktAgents =new SktAgents();
			if (alevel==10){
				sktAgents.setProvinceId(provinceId);
				sktAgents.setAlevel(alevel);
				EntityWrapper<SktAgents> entityWrapper=new EntityWrapper<SktAgents>(sktAgents);
				sktAgents = iSktAgentsService.selectOne(entityWrapper);
			}else if (alevel==11){
				if ("".equals(cityId)){
					map.put("code","00");
					map.put("msg","为选中市级区域");
					return map;
				}
				sktAgents.setCityId(cityId);
				sktAgents.setAlevel(alevel);
				EntityWrapper<SktAgents> entityWrapper=new EntityWrapper<SktAgents>(sktAgents);
				sktAgents = iSktAgentsService.selectOne(entityWrapper);
			}else if (alevel==12){
				if ("".equals(areaId)){
					map.put("code","00");
					map.put("msg","为选中县级区域");
					return map;
				}
				sktAgents.setAreaId(areaId);
				sktAgents.setAlevel(alevel);
				EntityWrapper<SktAgents> entityWrapper=new EntityWrapper<SktAgents>(sktAgents);
				sktAgents = iSktAgentsService.selectOne(entityWrapper);
			}
			if (sktAgents==null){
				map.put("code","00");
				map.put("msg","该地区代理公司不存在");
				return map;
			}
			Integer agentId=sktAgents.getAgentId();
			SktAgentsAccount agentsAccount=new SktAgentsAccount();//代理公司账号
			agentsAccount.setAgentId(agentId);
			EntityWrapper<SktAgentsAccount> wep=new EntityWrapper<SktAgentsAccount>(agentsAccount);
			SktAgentsAccount sktAgentsAccount = sktAgentsAccountService.selectOne(wep);
			//核对该公司想要申请的职位是否有空缺
			SktAgentsStockholder sktAgentsStockholder =new SktAgentsStockholder();
			sktAgentsStockholder.setAgentId(agentId);
			sktAgentsStockholder.setType(type);
			EntityWrapper<SktAgentsStockholder> ew=new EntityWrapper<SktAgentsStockholder>(sktAgentsStockholder);
			SktAgentsStockholder sktAgentsStockholder1 = this.selectOne(ew);
			if(sktAgentsStockholder1!=null){
				map.put("code","00");
				map.put("msg","您申请的职位暂无空缺");
				return map;
			}
			//判断是否是该公司股东
			SktAgentsStockholder sktAgentsStockholder3 =new SktAgentsStockholder();
			sktAgentsStockholder3.setAgentId(agentId);
			sktAgentsStockholder3.setUserId(userId);
			EntityWrapper<SktAgentsStockholder> ewr=new EntityWrapper<SktAgentsStockholder>(sktAgentsStockholder3);
			SktAgentsStockholder sktAgentsStockholder2 = this.selectOne(ewr);
			if (sktAgentsStockholder2!=null){
				if (sktAgentsStockholder2.getType()!=7){
					map.put("code","00");
					map.put("msg","普通用户或普通股东才能申请该职位");
					return map;
				}

			}
			if (type==1){//董事长任命
				if (sktAgents.getGPsurplusStockNum()<5){
					map.put("code","00");
					map.put("msg","管理股东剩余分数不足");
					return map;
				}
				Integer agencyFee = sktAgents.getAgencyFee();//每股缴纳代理费
				BigDecimal agencyScore=new BigDecimal(agencyFee).multiply(new BigDecimal(100));//每股获得积分数
				if (sktAgentsStockholder2!=null){//普通股东升级
					if (sktAgentsStockholder2.getType()==7){
						//插入变更表
						SktAgentsChanges transferAgentChenge = getAgentChenge( agentId, 1, userId, type, 7,4);
						sktAgentsChangesService.insert(transferAgentChenge);
						//修改申请表 远PHP逻辑没有
//						AgentsApplys agentsApplys=new AgentsApplys();
//						agentsApplys.setAgentId(agentId);
//						agentsApplys.setUserId(userId);
//						agentsApplys.setStatus(3);
//						EntityWrapper<AgentsApplys>  eWrapper=new EntityWrapper<AgentsApplys>(agentsApplys);
//						AgentsApplys agentsApplys1 = agentsApplysService.selectOne(eWrapper);
//						Calendar c = Calendar.getInstance();
//						c.setTime(new Date());//设置日历时间
//						c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
//						Date testTime=c.getTime();
//						agentsApplys1.setTestTime(testTime);
//						agentsApplys1.setBatFlag(1);
//						agentsApplys1.setBatTime(testTime);
//						agentsApplys1.setType(type);
//						agentsApplys1.setStockNum(5);
//						int moneys=5*agencyFee;
//						BigDecimal money=new BigDecimal(moneys);
//						agentsApplys1.setMoney(money);
//						agentsApplys1.setRemark("股东升级");
//						agentsApplysService.updateById(agentsApplys1);
						//更改股东表
						sktAgentsStockholder2.setStockNum(5);
						sktAgentsStockholder2.setType(1);
						this.updateById(sktAgentsStockholder2);
						//更新代理公司剩余股份数
						sktAgents.setLPsurplusStockNum(sktAgents.getLPsurplusStockNum()+1);
						sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()-5);
						iSktAgentsService.updateById(sktAgents);

						//给本人发几份
						Account account=new Account();
						account.setUserId(userId);
						EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
						Account account1 = accountService.selectOne(entityWrapper);
						BigDecimal scoreAdd= new BigDecimal(agencyFee).multiply(new BigDecimal(100));//补交代理费所得积分
						//积分流水
						accountService.insertLogScore(0,9, transferAgentChenge.getChangeNo(),account1.getScore(),"升级代理公司股东，赠送积分到积分账户",scoreAdd,1,userId);
						account1.setScore(account1.getScore().add(scoreAdd));
						account1.setTotalScore(account1.getTotalScore().add(scoreAdd));
						accountService.updateById(account1);
						//给上线发积分
						int inviteId = users.getInviteId();
						if (inviteId != 0) {
							Users inviteUsers = iUsersService.selectById(inviteId);
							if (inviteUsers.getUserType() == 2 && inviteUsers.getIsAgent() != 0) {
								BigDecimal	doubelScore=scoreAdd.multiply(new BigDecimal(2));
								Account accountInvite1=new Account();
								accountInvite1.setUserId(userId);
								EntityWrapper<Account> ewe=new EntityWrapper<Account>(accountInvite1);
								Account accountInvite = accountService.selectOne(ewe);
								accountService.insertLogScore(userId, 10, transferAgentChenge.getChangeNo(),
										accountInvite.getScore(), "下线升级代理奖励",doubelScore, 1, inviteId);
								accountInvite.setScore (accountInvite.getScore().add(doubelScore));
								accountInvite.setTotalScore (accountInvite.getTotalScore().add(doubelScore));
								accountService.updateById(accountInvite);
							}
						}
						//判断代理公司账户是否开启
						Integer runFlag=sktAgentsAccount.getRunFlag();
						if (runFlag==1){
							accountService.insertScoreAgent(3,agentId,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),1,scoreAdd,"代理升级，代理公司获得");
							sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(scoreAdd));
							sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(scoreAdd));
							sktAgentsAccountService.updateById(sktAgentsAccount);
						}else{
							//accountService.insertLogScoreFreeze(0,9,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),"代理升级，代理公司获得",scoreAdd,1,userId);
							accountService.insertScoreAgent(2,agentId,transferAgentChenge.getChangeNo(),sktAgentsAccount.getFreezeScore(),1,scoreAdd,"代理升级，代理公司获得待发积分");
							sktAgentsAccount.setFreezeScore(sktAgentsAccount.getFreezeScore().add(scoreAdd));
							sktAgentsAccountService.updateById(sktAgentsAccount);
						}
						//检查开启代理公司运营账号货分红账号
						Map<String, Object> map1 = checkRunOrProfit(agentId, transferAgentChenge.getChangeNo());
						if ("00".equals(map1.get("code").toString())){
							return map1;
						}
					}


				}else{//普通用户升级
					//插入变更表
//				SktAgentsChanges transferAgentChenge = getAgentChenge( agentId, 4, userId, type, 0,5);
//				sktAgentsChangesService.insert(transferAgentChenge);
					Calendar c = Calendar.getInstance();
					c.setTime(new Date());//设置日历时间
					c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
					Date testTime=c.getTime();
					//插入申请表
					AgentsApplys agentsApplys=getAgentsApplys(agentId,userId,users.getUserPhone(),1,5,new BigDecimal(agencyFee).multiply(new BigDecimal(5)),"成为代理公司股东",3,staffId,
							new Date(),staffId,new Date(),testTime,testTime);
					agentsApplysService.insert(agentsApplys);
					//生成代理公司股东表
					SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
					agentsStockholder.setAgentId(agentId);
					agentsStockholder.setType(type);
					agentsStockholder.setCreateTime(new Date());
					agentsStockholder.setStockNum(5);
					Integer countIsStore = iUsersService.selectCountIsStore (userId);
					agentsStockholder.setStoreNum(countIsStore);
					agentsStockholder.setUserId(userId);
					this.insert(agentsStockholder);
					//更新代理公司剩余股份数
					sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()-5);
					sktAgents.setStockNum(sktAgents.getStoreNum()+1);
					iSktAgentsService.updateById(sktAgents);
					//给本人发几份
					Account account=new Account();
					account.setUserId(userId);
					EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
					Account account1 = accountService.selectOne(entityWrapper);
					BigDecimal scoreAdd= new BigDecimal(agencyFee).multiply(new BigDecimal(100));//补交代理费所得积分
					//积分流水
					accountService.insertLogScore(0,9, agentsApplys.getOrderNo(),account1.getScore(),"升级代理公司股东，赠送积分到积分账户",scoreAdd,1,userId);
					account1.setScore(account1.getScore().add(scoreAdd));
					account1.setTotalScore(account1.getTotalScore().add(scoreAdd));
					accountService.updateById(account1);
					//给上线发积分
					int inviteId = users.getInviteId();
					if (inviteId != 0) {
						Users inviteUsers = iUsersService.selectById(inviteId);
						if (inviteUsers.getUserType() == 2 && inviteUsers.getIsAgent() != 0) {
							BigDecimal	doubelScore=scoreAdd.multiply(new BigDecimal(2));
							Account accountInvite1=new Account();
							accountInvite1.setUserId(userId);
							EntityWrapper<Account> ewpe=new EntityWrapper<Account>(accountInvite1);
							Account accountInvite = accountService.selectOne(ewpe);
							accountService.insertLogScore(userId, 10, agentsApplys.getOrderNo(),
									accountInvite.getScore(), "下线升级代理奖励",doubelScore, 1, inviteId);
							accountInvite.setScore (accountInvite.getScore().add(doubelScore));
							accountInvite.setTotalScore (accountInvite.getTotalScore().add(doubelScore));
							accountService.updateById(accountInvite);
						}
					}
					//判断代理公司账户是否开启
					Integer runFlag=sktAgentsAccount.getRunFlag();
					if (runFlag==1){
						accountService.insertScoreAgent(3,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getScore(),1,scoreAdd,"代理升级，代理公司获得");
						sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(scoreAdd));
						sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(scoreAdd));
						sktAgentsAccountService.updateById(sktAgentsAccount);
					}else{
						//accountService.insertLogScoreFreeze(0,9,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),"代理升级，代理公司获得",scoreAdd,1,userId);
						accountService.insertScoreAgent(2,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getFreezeScore(),-1,scoreAdd,"代理升级，代理公司获得待发积分");
						sktAgentsAccount.setFreezeScore(sktAgentsAccount.getFreezeScore().add(scoreAdd));
						sktAgentsAccountService.updateById(sktAgentsAccount);
					}
					//检查开启代理公司运营账号货分红账号
					Map<String, Object> map1 = checkRunOrProfit(agentId, agentsApplys.getOrderNo());
					if ("00".equals(map1.get("code").toString())){
						return map1;
					}

				}
				//修改用户信息
				users.setIsAgent(1);
				iUsersService.updateById(users);


			}else if (type==6){
				if (sktAgentsStockholder2!=null){
					map.put("code","00");
					map.put("msg","普通/管理股东不能成为监事");
					return map;
				}
				//插入变更表
				SktAgentsChanges transferAgentChenge = getAgentChenge( agentId, 4, userId, 0, 6,0);
				sktAgentsChangesService.insert(transferAgentChenge);
				//插入申请表
				Calendar c = Calendar.getInstance();
				c.setTime(new Date());//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				Date testTime=c.getTime();
				//插入申请表
				AgentsApplys agentsApplys=getAgentsApplys(agentId,userId,users.getUserPhone(),6,0,new BigDecimal(0),"任命为代理公司监事",3,1,
						new Date(),1,new Date(),testTime,testTime);
				agentsApplysService.insert(agentsApplys);
				//生成代理公司股东表
				SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				agentsStockholder.setCreateTime(new Date());
				agentsStockholder.setStockNum(0);
				Integer countIsStore = iUsersService.selectCountIsStore (userId);
				agentsStockholder.setStoreNum(countIsStore);
				agentsStockholder.setUserId(userId);
				this.insert(agentsStockholder);
				//修改用户信息
				users.setIsAgent(6);
				iUsersService.updateById(users);
				//更新代理公司股东人数
				sktAgents.setStockNum(sktAgents.getStoreNum()+1);
				iSktAgentsService.updateById(sktAgents);
				//检查开启代理公司运营账号货分红账号
				Map<String, Object> map1 = checkRunOrProfit(agentId, agentsApplys.getOrderNo());
				if ("00".equals(map1.get("code").toString())){
					return map1;
				}
			}
			map.put("code","01");
			map.put("msg","操作成功");
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","操作失败");
		}
		return  map;
	}
	//生成代理申请表
	public AgentsApplys getAgentsApplys(Integer agentId,Integer userId,String phone,Integer type, Integer stockNum,BigDecimal money,String remark,Integer status,
										Integer oneCheckStaffId,Date oneCheckTime,Integer twoCheckStaffId,Date twoCheckTime,Date testTime,Date batTime){
		AgentsApplys agentsApplys=new AgentsApplys();
		String orderNo = StringUtils.getOrderIdByTime("4");
		agentsApplys.setOrderNo(orderNo);
		agentsApplys.setAgentId(agentId);
		agentsApplys.setUserId(userId);
		agentsApplys.setPhone(phone);
		agentsApplys.setType(type);
		agentsApplys.setStockNum(stockNum);
		agentsApplys.setMoney(money);
		agentsApplys.setRemark(remark);
		agentsApplys.setStatus(status);
	//	agentsApplys.setMoneyOrderImg();
		agentsApplys.setCreateTime(new Date());
	//	agentsApplys.setCheckRemark();
		agentsApplys.setOneCheckStaffId(oneCheckStaffId);
		agentsApplys.setOneCheckTime(oneCheckTime);
		agentsApplys.setTwoCheckStaffId(twoCheckStaffId);
		agentsApplys.setTwoCheckTime(twoCheckTime);
		agentsApplys.setTestTime(testTime);
		agentsApplys.setBatFlag(1);
		agentsApplys.setBatTime(batTime);
		return agentsApplys;
	}
	/**
	 * 确认代理申请
	 * @param shaId 股东申请表id
	 * @param staffId  操作员id
	 * @return
	 */
	@Override
	@Transactional
	public Map<String,Object> applysSetStatus(Integer shaId,Integer staffId){
		Map<String,Object> map=new  HashMap();
		try{
			AgentsApplys agentsApplys = agentsApplysService.selectById(shaId);
			BigDecimal money = agentsApplys.getMoney();
			int userId = agentsApplys.getUserId();
			int agentId = agentsApplys.getAgentId();
			int type = agentsApplys.getType();
			//查询申请人
			Users users = iUsersService.selectById(userId);
			//申请人账户
			Account account=new Account();
			account.setUserId(userId);
			EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
			Account account1 = accountService.selectOne(entityWrapper);
			//推荐人id
			int inviteId = users.getInviteId();
			//查询代理公司
			SktAgents sktAgents = iSktAgentsService.selectById(agentId);
			if (sktAgents==null){
				map.put("code","00");
				map.put("msg","该代理公司不存在");
				return  map;
			}
			//	Integer agencyFee = sktAgents.getAgencyFee();//每股缴纳代理费
			//判断是否是该公司股东
			SktAgentsStockholder sktAgentsStockholder3 =new SktAgentsStockholder();
			sktAgentsStockholder3.setAgentId(agentId);
			sktAgentsStockholder3.setUserId(userId);
			EntityWrapper<SktAgentsStockholder> ewr=new EntityWrapper<SktAgentsStockholder>(sktAgentsStockholder3);
			SktAgentsStockholder sktAgentsStockholder2 = this.selectOne(ewr);
			if(sktAgentsStockholder2!=null){
				map.put("code","00");
				map.put("msg","该用户已经是该公司股东，不能在申请该公司股东");
				return  map;
			}
			SktAgentsAccount agentsAccount=new SktAgentsAccount();//代理公司账号
			agentsAccount.setAgentId(agentId);
			EntityWrapper<SktAgentsAccount> wep=new EntityWrapper<SktAgentsAccount>(agentsAccount);
			SktAgentsAccount sktAgentsAccount = sktAgentsAccountService.selectOne(wep);
			//查询股东发展商家数量
			Integer countIsStore = iUsersService.selectCountIsStore (userId);
			Integer lPsurplusStockNum = sktAgents.getLPsurplusStockNum();
			Integer gPsurplusStockNum = sktAgents.getGPsurplusStockNum();
			if (type==7){
				if (lPsurplusStockNum==0){
					map.put("code","00");
					map.put("msg","该地区普通股东已满");
					return  map;
				}
				//修改代理公司表
				sktAgents.setLPsurplusStockNum(sktAgents.getLPsurplusStockNum()-1);
				sktAgents.setStockNum(sktAgents.getStoreNum()+1);
				sktAgents.setStoreNum(sktAgents.getStoreNum()+countIsStore);
				iSktAgentsService.updateById(sktAgents);
				//修改申请表
				agentsApplys.setBatFlag(0);
				agentsApplysService.updateById(agentsApplys);
				//分红股东赠送上线双倍积分到积分账户
				//给上线发积分（经理或者代理）

				if (inviteId != 0) {
					Users inviteUsers = iUsersService.selectById (inviteId);
					//如果是主管申请代理判断下线7个工作日内是否有下线代理申请通过  如果有赠送双倍积分 begin
					if (users.getUserType() != 2) {
						//前七个工作日代理通过
						List<AgentsApplys> list = accountService.getAgentsApplysSevenAgo (userId);
						if (list != null && list.size() > 0) {
							BigDecimal sumScore = BigDecimal.ZERO;
							BigDecimal sumScoreFreeze = BigDecimal.ZERO;
							for (AgentsApplys AgentsApply : list) {
								sumScore = sumScore.add (AgentsApply.getMoney().multiply(new BigDecimal("200")));
							}
							if(sumScore.compareTo(BigDecimal.ZERO)==1){
								accountService.insertLogScore(userId, 10, agentsApplys.getOrderNo(), account1.getScore(), "被分享人升级为分红股东，赠送双倍积分到积分账户", sumScore, 1, userId);
								account1.setScore(account1.getScore().add (sumScore));
								account1.setTotalScore (account.getTotalScore().add(sumScore));
							}
//						am.updateById(account);
						}
					}
					//end
					//上线为股东或者经理赠送上线双倍积分 begin
					if (inviteUsers.getUserType() == 2 || inviteUsers.getIsAgent() != 0) {
						Account accountInvite = accountService.selectAccountByuserId(inviteId);
						BigDecimal doubelScore = money.multiply(new BigDecimal("200"));
						accountService.insertLogScore(userId, 10, agentsApplys.getOrderNo(), accountInvite.getScore(), "被分享人升级为分红股东，赠送双倍积分到积分账户", doubelScore, 1, inviteId);
						accountInvite.setScore (accountInvite.getScore().add(doubelScore));
						accountInvite.setTotalScore (accountInvite.getTotalScore().add(doubelScore));
						accountService.updateById(accountInvite);
					}
					//end
				}
			}
			if (type != 6 && type != 7) {
				SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				Integer countStcokManger = sktAgentsStockholderMapper.selectCountStcokManger(agentsStockholder);
				if (type == 1 && countStcokManger == 1) {
					map.put("code","00");
					map.put("msg","该地区董事长职位已满");
					return  map;
				} else if (type == 2 && countStcokManger == 1) {
					map.put("code","00");
					map.put("msg","该地区总裁职位已满");
					return  map;
				} else if (type == 3 && countStcokManger == 1) {
					map.put("code","00");
					map.put("msg","该地区普行政职位已满");
					return  map;
				} else if (type == 4 && countStcokManger == 1) {
					map.put("code","00");
					map.put("msg","该地区财务职位已满");
					return  map;
				} else if (type == 5 && countStcokManger == 3) {
					map.put("code","00");
					map.put("msg","该地区部门经理职位已满");
					return  map;
				}
				sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()-1);
				iSktAgentsService.updateById(sktAgents);
				//修改申请表
				agentsApplys.setBatFlag(1);
				Date batTime = agentsApplys.getBatTime();
				Calendar c = Calendar.getInstance();
				c.setTime(batTime);//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				agentsApplys.setTestTime(c.getTime());
				//	agentsApplys.setBatTime(c.getTime());
				agentsApplysService.updateById(agentsApplys);
//				insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(), account.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1, userId);
//				account.setFreezeScore(account.getFreezeScore().add(money.multiply(new BigDecimal("100"))));
//				am.updateById(account);

			}
			//修改用户信息
			users.setIsAgent(type);
			iUsersService.updateById(users);
			//生成代理公司股东表
			SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
			agentsStockholder.setAgentId(agentId);
			agentsStockholder.setType(type);
			agentsStockholder.setCreateTime(new Date());
			agentsStockholder.setStockNum(5);
			agentsStockholder.setStoreNum(countIsStore);
			agentsStockholder.setUserId(userId);
			this.insert(agentsStockholder);
			//给本人发几份
			BigDecimal scoreAdd=money.multiply(new BigDecimal(100));//代理费所得积分
			//积分流水
			accountService.insertLogScore(0,9,agentsApplys.getOrderNo(),account1.getScore(),"升级代理公司股东，赠送积分到积分账户",scoreAdd,1,userId);
			account1.setScore(account1.getScore().add(scoreAdd));
			account1.setTotalScore(account1.getTotalScore().add(scoreAdd));
			accountService.updateById(account1);
			//判断代理公司账户是否开启 如果开启赠送到积分账户，关闭赠送到待发积分账户
			Integer runFlag=sktAgentsAccount.getRunFlag();
			if (runFlag==1){
				accountService.insertScoreAgent(1,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getScore(),1,scoreAdd,"代理通过，代理公司获得");
				sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(scoreAdd));
				sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(scoreAdd));
				sktAgentsAccountService.updateById(sktAgentsAccount);
			}else{
				//accountService.insertScoreAgent(0,9,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),"代理升级，代理公司获得",scoreAdd,1,userId);
				accountService.insertScoreAgent(2,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getFreezeScore(),1,scoreAdd,"代理通过，代理公司获得待发积分");
				sktAgentsAccount.setFreezeScore(sktAgentsAccount.getFreezeScore().add(scoreAdd));
				sktAgentsAccountService.updateById(sktAgentsAccount);
			}
			//检查开启代理公司运营账号货分红账号
			Map<String, Object> map1 = checkRunOrProfit(agentId, agentsApplys.getOrderNo());
			if ("00".equals(map1.get("code").toString())){
				return map1;
			}
			map.put("code","01");
			map.put("msg","操作成功");
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","操作失败");
		}
		return  map;
	}
}
